<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\api\model;

use app\api\controller\Viator;
use think\Db;
use \think\Model;
use app\admin\controller\Membertype;
use app\api\model\Standard as SDModel;
use think\Exception;

class Goods extends Model
{
    public function goodsdetails($t='',$openid){
        $shu=[];
        $price='';
        $schedule='';
        $img='';
        $img1='';
        $stroke='';
        $qujian='';
        $qujian1='';
        $qujian2='';
        $max='';
        $max1='';
        $min1='';
        $min='';
        $yuanjia='';
        if ($t!==''){
            $id=$t;
            $goods= $this->where('goods_id',$id)->find();//查询商品

            $member=model('Member')
                ->where('program_openid',$openid)
                ->find();

//            $discoun_per=db('member_type')->where('member_type_id', $member['member_type_id'])->field('discoun_per')->find();
            $Membertype = new Membertype();
            $discoun_per_arr = $Membertype->get_discoun_per($member['member_id']);//获取折扣集
            //该类型商品的折扣率
            $discoun_per = isset($discoun_per_arr[$goods['classify_id']]) ? $discoun_per_arr[$goods['classify_id']] : '';

            $len= strlen($goods['tag_id']);
            $tag='';
            if ($len>1){
                $tag_id=explode(',',$goods['tag_id']);
                foreach ($tag_id as $t){
                    $tag1=model('Tag')->where('tag_id',$t)->field('tag_id,tag_name')->find();//tag 标签
                    $tag[]=[
                        'tag_id'=>$tag1['tag_id'],
                        'tag_name'=>$tag1['tag_name'],
                    ];
//                    $tag[]['tag_name']=$tag1['tag_name'];
                }
            }else if($len>0){
                $tag=model('Tag')->where('tag_id',$goods['tag_id'])->field('tag_id,tag_name')->select();//tag 标签
            }

            $zuizao='';
            if (time()>$goods['starttime'] && time()<$goods['endtime'] ){
                $zuizao='今天';
            }else if(time()<$goods['starttime']){
                $zuizao=date('Y-m-d',$goods['starttime']);
            }else{
                $zuizao='未知';
            }

            $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
            if(!empty($goods['price'])){
                $qujian=ceil($goods['price']*$exchange['exchange_rate']);
                if (!empty($discoun_per)){
                    $qujian=ceil($qujian*$discoun_per);
                }
                $Viator=  new Viator();

                $month=date('m',time());
                $data1= $Viator->getPriceShow($goods['code'],$month);
//                foreach ($data1 as $s=>$v){
//                dump($data1);
                if (!empty($data1)){
                    $zuizao=  $data1[0]['bookingDate'];
                }

//            $goods['goods_name'] = $Viator->etoc($goods['goods_name']);
//            $goods['goods_introduce'] = $Viator->etoc($goods['goods_introduce']);
            }
            else {

            //获取价格区间

                $specs = db('Specs')->alias('s')
                    ->where('s.goods_id', $goods['goods_id'])
                    ->where('s.specs_status', '1')
                    ->join('Person p', 's.specs_id=p.specs_id')
//                        ,['s.specs_status',1]
                    ->where('p.person_status', '1')
//                        ->where('p.person_name','1')
                    ->field('p.person_price')
                    ->select();
                if ($specs == false) {

                    $shu = [
                        'code' => 0,
                        'msg' => '啊哦~没有商品数据哦',
                    ];

                    return $shu;
                    die;
                }

                if (!empty($specs)) {
                    foreach ($specs as $k => $v) {
                        $price[] = $v['person_price'];
                    }
                    $max = ceil(max($price));
                    $min = ceil(min($price));

                    if (!empty($discoun_per)) {
                        $qujian = ceil(($min * $discoun_per)) . '~' . ceil(($max * $discoun_per));

                        if ($min == ceil(($min * $discoun_per)) and $max == ceil(($max * $discoun_per))) {
                            $qujian2 = "";
                        } else {
                            $qujian2 = "$min~$max";
                        }


                        if ($max == $min) {
                            $qujian = ceil($min * $discoun_per);
                            $qujian2 = $min;
                        }

                    } else {
                        $qujian = "$min~$max";
                        $qujian2 = "";
                        if ($max == $min) {

                            $qujian = $min;
                            $qujian2 = '';
                        }

                    }

                }
            }
            $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
            //商品购买页推荐
            $tuijian=  $this->where('goods_location',$goods['goods_location'])->where('goods_source',1)->where('goods_status',1)->limit(4)->select();
            foreach ($tuijian as $k=>$t) {
                if ($t['goods_id'] != $goods['goods_id']) {
                    if(!empty($t['price'])){
                        $qujian1=$t['price']*$exchange['exchange_rate'];
                        if (!empty($discoun_per)){
                            $qujian1=  ceil( $discoun_per*$qujian1);
                        }

                    }else {
                        $specs1 = db('Specs')->alias('s')
                            ->where('s.goods_id', $t['goods_id'])
                            ->where('s.specs_status', '1')
                            ->join('Person p', 's.specs_id=p.specs_id')
                            ->where('p.person_status', '1')
                            ->field('p.person_price')
                            ->select();
                        $price1 = [];
                        if (!empty($specs1)) {
                            foreach ($specs1 as $k => $v) {
                                $price1[] = $v['person_price'];
                            }
                            $max1 = ceil(max($price1));
                            $min1 = ceil(min($price1));

                            if (!empty($discoun_per)) {
                                $qujian1 = ceil(($min1 * $discoun_per)) . '~' . ceil(($max1 * $discoun_per));
                                if ($max1 == $min1) {

                                    $qujian1 = ceil(($min1 * $discoun_per));
                                }


                            } else {
                                $qujian1 = "$min1~$max1";
                                if ($max1 == $min1) {

                                    $qujian1 = $min1;
                                }
                            }

                        }

                    }


                    $imgs = !empty($t['goods_image']) ? explode(',', $t['goods_image']) : '';

                    if ( !empty($imgs)) {
//                                        dump($imgs);
                        $imgs = !empty($imgs[1])?$imgs[1]:$imgs[0];
                    } else {
                        $imgs = '';
                    }

                    $stroke['tuijian'][] = [
                        'goods_id' => $t['goods_id'],
                        'jiage' => $qujian1,
                        'name' => $t['goods_name'],
                        'image' => $imgs
                    ];

                }
            }

            //评论
            $comment=db('comment')
                ->alias('a')
                ->join('member d','a.member_id=d.member_id')
                ->join('attachment b','b.id=d.thumb')
                ->where('a.goods_id',$id)
                ->where('a.comment_status',2)
                ->field('a.content,a.creattime,a.comment_img')
                ->field('a.content,a.creattime,d.member_nickname,b.filepath as touxiang,a.comment_img')
                ->order('a.creattime desc')
                ->limit(3)
                ->select();


//                          dump($comment);
            $pinglun=[];
            if (!empty($comment)){

                foreach ($comment as $c){


                    if(!empty($c['comment_img'])){
                        $img1= explode(',',$c['comment_img']);
                        if ($img1!=''){
                            $img1= array_filter($img1);
                        }else{
                            $img1= '';
                        }
                    }

                    $pinglun[]= [
                        'content'=>$c['content'],
                        'creattime'=>date('Y-m-d H:i:s',$c['creattime']),
                        'member_nickname'=>$c['member_nickname'],
                        'touxiang'=>$c['touxiang'],
                        'img'=>$img1
                    ];
                }
            }else{
                $pinglun='';
            }

            //图片路径处理
            $image=!empty($goods['goods_image'])?explode(',',$goods['goods_image']):'';

            if ($image!=''){
                $image= array_filter($image);
//                foreach ($image as $l=>$v){
//
//                }
            }else{
                $image= '';
            }
            $video=!empty($goods['goods_video'])?$goods['goods_video']:'';
            $Sales=db('order')->where('goods_id',$id)
                ->where('order_status',2)
                ->whereOr('order_status',3)
                ->whereOr('order_status',4)
                ->count();



            $collection=model('Collection')->where('goods_id',$goods['goods_id'])
                ->where('collection_types',1)->where('member_id',$member['member_id'])->find();

            if (!empty($collection)){
                $collection=1;
            }else{
                $collection=0;
            }

            $shu=[
                'code'=>0,
                'msg'=>'ok',
                'data'=>[
                    'goods_id'=>$goods['goods_id'],
                    'jiagequjian'=>$qujian,
                    'Sales'=>$Sales,
                    'zuizao'=>$zuizao,
                    'collection'=>$collection,
                    'yuanjia'=>$qujian2,
                    'img'=>[ 'image'=>$image,'video'=>$video],
                    'title'=>$goods['goods_name'],
                    'Englishtitle'=>$goods['goods_englishname'],
                    'tag'=>$tag,
                    'goods_introduce'=>$goods['goods_introduce'],//产品介绍
                    'stroke'=>$stroke,//行程或poi、
                    'price_include'=>$goods['price_include'],//费用包含
                    'price_noinclude'=>$goods['price_noinclude'],//费用不含
                    'goods_careful'=>$goods['goods_careful'],//注意事项
                    'goods_retreating'=>$goods['goods_retreating'],//退改规则
                    'pinglun'=>$pinglun
                ]
            ];





        }else{
            $shu=[
                'code'=>101,
                'msg'=>'非法参数',
            ];




        }

//        max($price)
        return $shu;
    }
    
    
    /*
       * $goods_id 商品id
       * $openid 小程序 用户辨识id
       * $specs_id 规格ID
       *
       *
       * */
    public function package($goods_id,$specs_id,$openid){
        $data = [];
        $mk_shuzu = '';
        $member = model('Member')
            ->where('program_openid',$openid)
            ->find();
        $Membertype = new Membertype();
        $discoun_per_arr = $Membertype->get_discoun_per($member['member_id']);//获取折扣集
        $goods = db('goods')->where('goods_id',$goods_id)->find();
        //该类型商品的折扣率
        $discoun_per = isset($discoun_per_arr[$goods['classify_id']]) ? $discoun_per_arr[$goods['classify_id']] : '';
        if (empty($specs_id)){
            $sp=model('Specs')
                ->where('goods_id',$goods_id)
                ->where('specs_status',1)
                ->where('specs_types',1)
                ->field('specs_id,specs_name,specs_types')
                ->select();

            foreach ($sp as $s){
                $ce = model('Person')
                    ->where('specs_id',$s['specs_id'])
                    ->where('person_status', 1)
//                        ->field('person_name,person_num,person_price')
                    ->select();
                if (!empty($ce)){
                    $data['specs'][]=$s;
                }
            }
        }else{
            $sp=model('Specs')
                ->where('goods_id',$goods_id)
                ->where('specs_status',1)
                ->where('specs_types',1)
                ->field('specs_id,specs_name,specs_types')
                ->select();
            foreach ($sp as $s){
                $ce = model('Person')
                    ->where('specs_id',$s['specs_id'])
                    ->where('person_status', 1)
//                        ->field('person_name,person_num,person_price')
                    ->select();
                if (!empty($ce)){
                    $data['specs'][]=$s;
                }

            }
//            $data['specs']=$sp;
            //获取活动
            $mk=model('Marketing')
                ->where('goods_id',$goods_id)
                ->where('mk_status',1)
                ->find();
            //获取商品
            $goods=$this->where('goods_id',$goods_id)
                ->field('starttime,endtime,tag_id')
                ->find();
            //商品售卖开始时间结束时间
            $kaishi=$goods['starttime'];
            $jieshu=$goods['endtime'];
            $tian=($jieshu-$kaishi)/60/60/24;
            //活动开始结束时间
            $mk_kaishi=$mk['mk_starttime'];
            $mk_jieshu=$mk['mk_endtime'];
            $mk_tian=round(($mk_jieshu-$mk_kaishi)/60/60/24);
            //判断是否是活动
            $shuliang=0;
            $Person=[];
            if (!empty($mk)||$mk==true){
//                $len= strlen($mk['specs_id']);
//                if ($len>1){
//                    $mk_specs_id=  explode(',',$mk['specs_id']);
//                    $mk_specs_id=array_filter($mk_specs_id);

                $mk_specs_id=  db('specs')->where('pid',$specs_id)->where('specs_status',1)->select();

                foreach ($mk_specs_id as $v){
                    $Person1 = model('Person')
                        ->where('specs_id',$v['specs_id'])
                        ->where('person_status', 1)
                        ->field('person_id,person_name,person_num,person_price')
                        ->select();
                    foreach ($Person1 as $g){
                        $Person[]=$g;
                    }

                }
//                    $data['Person'] = $Person;
//                    dump($mk_specs_id);
//                }

//            dump($Person);die;
                $min=0;
                if (!empty($Person)){
                    foreach ($Person as $k=>$v){
                        $price[]=$v['person_price'];
                        if (!empty($discoun_per)){
                            $Person[$k]['person_price']= ceil((float)$v['person_price']*(float)$discoun_per);
                        }
                        $shuliang+=(int)$v['person_num'];
                    }
                    $min= min($price);
                    if (!empty($discoun_per)){

                        $min=  ceil(($min*$discoun_per));
                    }
                }

                $g=0;
                for ($i=0;$i<$mk_tian;$i++){
                    $mk_shuzu[$i]=[
                        'shijian'=>date('Y-m-d',$mk_kaishi+$g),
                        'jiage'=>$min,
                        'Person'=>$Person
                    ];
                    $g+=86400;
                }

            }else{
                $Person = model('Person')
                    ->where('specs_id',$specs_id)
                    ->where('person_status', 1)
                    ->field('person_id,person_name,person_num,person_price')
                    ->select();
//                    $data['Person'] = $Person;
            }
            $Persons=model('Person')
                ->where('specs_id',$specs_id)
                ->where('person_status',1)
                ->field('person_id,person_price,person_num,person_name')
                ->select();
            $shuliang1=0;
            $z_min=0;
//            dump($Persons);
            if (!empty($Persons)){
                foreach ($Persons as $k=>$v){
                    $pricea[]=$v['person_price'];
                    if (!empty($discoun_per)){
                        $Person[$k]['person_price']= ceil((float)$v['person_price']*(float)$discoun_per);
                    }
                    $shuliang1+=(int)$v['person_num'];
                }
//                dump($Persons);
                $z_min= min($pricea);
                if (!empty($discoun_per)){

                    $z_min=  ceil($z_min*$discoun_per);
                }

            }
            $s=0;
            for ($i=0;$i<$tian;$i++){

                $shuzu[$i]=[
                    'shijian'=>date('Y-m-d',$kaishi+$s),
                ];
                $s+=86400;
            }
            $where['isdelete']=0;
            $where['refund_status']=0;//
            $where['order_status']=[['NEQ',6],['NEQ',7,'or']];//订单查询条件
            foreach ($shuzu as $k=>$v){
                if ($v['shijian']<$this->getNextMonthDays(date('Y-m-d',time()))){//获取数据限制 最长4个月


                    $xin[$k]['shijian']=$v['shijian'];

                    $maiqu= db('order')
                        ->where('goods_id',$goods_id)
                        ->where($where)
                        ->where('travel_date',$v['shijian'])
                        ->select();
                    $xin[$k]['shuliang']=$shuliang1;
                    $xin[$k]['Person']=$Persons;
//                    dump($Persons);

                    $yimai=0;

//                    $renshu=0;
                    $person_num=0;
                    $renshu2=[];
                    foreach ($maiqu as $s){//循环已有订单
                        $renshu=0;
                        if ($v['shijian']===$s['travel_date']){

                            $shengyu=db('orderperson')->where('order_id',$s['order_id'])->select();//获取订单详情
                            if(!empty($shengyu)){
                                foreach ($shengyu as $ff){
                                    $renshu2[]=[//组装每一天订单下面的规格详情
                                        'person_id' => $ff['person_id'],
                                        'person_price' =>$ff['person_price'],
                                        'person_num' =>$ff ['person_num'],
                                        'person_name' => $ff['person_name'],
                                        'chuxing' => $ff['chuxing'],
                                    ];
                                }
                            }
                        }

                    }
                    if (!empty($renshu2)){
                        $new = array();
                        foreach($renshu2 as $row){ //对每一天的订单规格详情进行去重 数量相加的操作
                            if(isset($new[$row['person_id']])){
                                $new[$row['person_id']]['person_num'] += $row['person_num'];
                            }else{
                                $new[$row['person_id']] = $row;
                            }
                        }
//                                dump($xin[$k]['Person']);
                        foreach ($Persons as $f=>$g){//计算商品剩余量
                            foreach ($new as $kk=>$hh){
                                if ($v['shijian']==$hh['chuxing']) {//判断时间
                                    if ($g['person_id'] == $hh['person_id']){//判断相等的详情id
//                                            dump($hh);
                                        $yimai+=$hh['person_num'];
                                        $xin[$k]['Person'][$f] = [
                                            'person_id' => $g['person_id'],
                                            'person_price' =>$g['person_price'],
                                            'person_num' => $g['person_num'] - $hh['person_num'],
                                            'person_name' => $g['person_name'],
                                        ];

                                    }
                                }

                            }


                        }
                    }

                    $xin[$k]['shuliang']=$shuliang1-$yimai;
                    $xin[$k]['jiage']=$z_min;
                    if (!empty($mk_shuzu)){//活动判断

                        foreach ($mk_shuzu as $t){
                            if ($v['shijian']==$t['shijian']){

                                $maiqu= db('order')
                                    ->where('goods_id',$goods_id)
                                    ->where($where)
                                    ->where('travel_date',$v['shijian'])
                                    ->select();

                                $xin[$k]['Person']=$t['Person'];

                                $xin[$k]['shuliang']=$shuliang;
                                $yimai=0;
                                foreach ($maiqu as $s){
                                    if ($t['shijian']===$s['travel_date']){
                                        $shengyu=db('orderperson')->where('order_id',$s['order_id'])->select();
                                        if(!empty($shengyu)){
                                            foreach ($shengyu as $ff){
                                                $renshu2[]=[
                                                    'person_id' => $ff['person_id'],
                                                    'person_price' =>$ff['person_price'],
                                                    'person_num' =>$ff ['person_num'],
                                                    'person_name' => $ff['person_name'],
                                                    'chuxing' => $ff['chuxing'],
                                                ];
                                            }
                                        }
                                    }

                                }

                                if (!empty($renshu2)) {

                                    $new = array();
                                    foreach ($renshu2 as $row) {
                                        if (isset($new[$row['person_id']])) {
                                            $new[$row['person_id']]['person_num'] += $row['person_num'];
                                        } else {
                                            $new[$row['person_id']] = $row;
                                        }
                                    }

                                    foreach ($t['Person'] as $f => $g) {
                                        foreach ($new as $kk => $hh) {
                                            if ($v['shijian'] == $hh['chuxing']) {
                                                if ($g['person_id'] == $hh['person_id']) {
                                                    $yimai += $hh['person_num'];

                                                    $xin[$k]['Person'][$f] = [
                                                        'person_id' => $g['person_id'],
                                                        'person_price' => $g['person_price'],
                                                        'person_num' => $g['person_num'] - $hh['person_num'],
                                                        'person_name' => $g['person_name'],
                                                    ];
                                                }
                                            }
                                        }
                                    }
                                }
                                $xin[$k]['shuliang']=$shuliang-$yimai;
                                $xin[$k]['jiage']=$t['jiage'];

                            }

                        }
                    }

                }




            }
            $data['riqijiage']=$xin;
        }
        return $data;
    }

    public function getNextMonthDays($date){
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = strtotime("$firstday +5 month -1 day");
        $day_lastday = date('d', $lastday); //获取下个月份的最后一天
        $day_benlastday = date('d', strtotime("$firstday +1 month -1 day")); //获取本月份的最后一天

        //获取当天日期
        $Same_day = date('d', strtotime($date));
        //判断当天是否是最后一天   或 下月最后一天 等于 本月的最后一天
        if($Same_day == $day_benlastday||$day_lastday == $Same_day){
            $day = $day_lastday;

        }else{
            $day = $Same_day;

        }
        $day = date('Y',$lastday).'-'.date('m',$lastday).'-'.$day;

        return $day;

    }

    public function classifypoi($t='',$city_id='',$lat2,$lng2,$openid){
        $id=$t;
        $data=[];
        $poi=model('Poi');

        if ($t!=0){
            $poi=$poi->where('typeid',$id);
        }
        if ($city_id!=0){
            $poi=$poi ->where('groupid',$city_id);
        }

        $poi=$poi->where('deleted',0)
                ->field('id,name,eng_name,lat,lng,thumb,score,total_score,total_comment_num,open_time')
            ->order('poi_sort desc,create_time desc')
                ->select();
        $member=model('Member')
            ->where('program_openid',$openid)
            ->find();

        $collection=model('Collection')->where('member_id',$member['member_id'])->select();

        foreach ($poi as $k=>$v){
            $data[$k]['poi_id']=$v['id'];
            $data[$k]['name']=$v['name'];
            $data[$k]['eng_name']=$v['eng_name'];
            $data[$k]['score']=$v['score'];
            $data[$k]['comment_score']=$v['total_comment_num']>0?ceil($v['total_score']*100/$v['total_comment_num'])/100:0;
            $data[$k]['total_comment_num']=$v['total_comment_num'];
            $data[$k]['open_time']=$v['open_time'];
            $data[$k]['collection']=0;
            if (!empty($collection)){
                foreach ($collection as $b){
                    if ($v['id']==$b['goods_id']){
                        $data[$k]['collection']='1';
                    }
                }
            }
            //计算距离
            if ($lat2!=0||$lng2!=0){
                $juli1= $this->getDistance($v['lat'],$v['lng'],$lat2,$lng2);
                $data[$k]['juli']=($juli1/1000);
            }else{
                $data[$k]['juli']='无法获取您的地理位置';
            }

            $img = !empty($v['thumb']) ? array_filter(explode(',', $v['thumb'])) : [];
            if (!empty($img)) {
                $v['thumb'] = array_shift($img);
            } else {
                $v['thumb'] = '';
            }
            $data[$k]['thumb'] = $v['thumb'];
        }

        return  $data;
    }

    //小程序POI
    public function program_classifypoi($t='',$city_id='',$lat2,$lng2,$openid,$page=1,$pageLimit=100){
        $id=$t;
        $data=[];
        $where = [];

        $where['deleted'] = 0;
        $where['is_stop'] = 0;
        if ($t!=0){
            $where['typeid'] = $id;
        }
        if ($city_id!=0){
            $where['groupid'] = $city_id;
        }

        $poiCount = db("poi")->where($where)->count();
        if($page==1 && $poiCount<$pageLimit*2){
            $pageLimit = 1000;
        }

        if ($page==1){
            $pages=0;
        }else{
            $pages= ($page-1)*$pageLimit;
        }

        $pageCount = 1;
        if($poiCount>0){
            $pageCount = ceil($poiCount/$pageLimit);
        }

        $poi=db("poi")
            ->where($where)
            ->field('id,name,eng_name,lat,lng,thumb,score,total_score,total_comment_num,open_time,cooking')
            ->order('poi_sort desc,create_time desc')
            ->limit($pages,$pageLimit)  //分页
            ->select();

        $member=model('Member')
            ->where('program_openid',$openid)
            ->find();

        $collection=model('Collection')->where('member_id',$member['member_id'])->select();

        foreach ($poi as $k=>$v){
            $data[$k]['poi_id']=$v['id'];
            $data[$k]['name']=$v['name'];
            $data[$k]['eng_name']=$v['eng_name'];
            $data[$k]['score']=$v['score'];
            $data[$k]['comment_score']=$v['total_comment_num']>0?ceil($v['total_score']*100/$v['total_comment_num'])/100:0;
            $data[$k]['total_comment_num']=$v['total_comment_num'];
            $data[$k]['open_time']=$v['open_time'];
            $data[$k]['cooking']=!empty($v['cooking']) ? $v['cooking'] : '';
            $data[$k]['collection']=0;
            if (!empty($collection)){
                foreach ($collection as $b){
                    if ($v['id']==$b['goods_id']){
                        $data[$k]['collection']='1';
                    }
                }
            }
            //计算距离
            if ($lat2!=0||$lng2!=0){
                $juli1= $this->getDistance($v['lat'],$v['lng'],$lat2,$lng2);
                $data[$k]['juli']=($juli1/1000);
            }else{
                $data[$k]['juli']='无法获取您的地理位置';
            }

            $img = !empty($v['thumb']) ? array_filter(explode(',', $v['thumb'])) : [];
            if (!empty($img)) {
                $v['thumb'] = array_shift($img);
            } else {
                $v['thumb'] = '';
            }
            $data[$k]['thumb'] = $v['thumb'];
        }

        $data1['page'] = $page;
        $data1['pageLimit'] = $pageLimit;
        $data1['pageCount'] = $pageCount;

        return ['data'=>$data,'data1'=>$data1];
    }

    public function getDistance($lat1, $lng1, $lat2, $lng2){
        $earthRadius = 6367000; //approximate radius of earth in meters
        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }

    //公式计算总价
    public function calculateTotalPrice(
        $vehicleCost,   //用车报价
        $vehicle_rate,  //用车利率
        $hotelCost,     //酒店单价【双人标间】
        $hotel_rate,    //酒店利率
        $ticketCost,    //门票单价
        $ticket_rate,   //门票利率
        $extraCost,     //额外利率
        $extra_rate,    //额外利率
        $peopleNum      //总人数
    )
    {
        $hotelRoomNum = ceil($peopleNum/2);//获取酒店的间数
        $totalVehicleCost = ceil($vehicleCost*$vehicle_rate*100)/100;
        $totalHotelCost = ceil($hotelCost*$hotelRoomNum*$hotel_rate*100)/100;
        $totalTicketCost = ceil($ticketCost*$peopleNum*$ticket_rate*100)/100;
        $totalExtraCost = ceil($extraCost*$extra_rate*100)/100;

        return ceil(($totalVehicleCost+$totalHotelCost+$totalTicketCost+$totalExtraCost)/$peopleNum);
    }

    //更新酒店利率 刷新酒店售价
    public function updHotelCost($goods_id,$hotel_rate)
    {
        $goods = db("goods")->find($goods_id);
        if(empty($goods_id) || empty($goods)) return false;
        $personday = db("personday")->where(['goods_id'=>$goods_id])->select();
        if(!empty($personday)) return false;
        foreach ($personday as $key=>$value){
            if(empty($value['hotel_json'])) continue;

            $hotel_json = json_decode($value['hotel_json'],true);
            if(empty($hotel_json)) continue;

            foreach ($hotel_json as $hotel_k=>$hotele_v){
                $amount = $hotele_v['cost']['amount']??0;
                if(empty($amount)) continue;

                //获取汇率
                $currency_code = $hotele_v['cost']['currency']??"USD";
                $exchange = db("exchange")->where(['currency_code'=>$currency_code])->find();
                $exchange_rate = $exchange['exchange_rate'];

                $hotel_json[$hotel_k]['price']  = sprintf("%.2f",$amount*$exchange_rate*$hotel_rate);
            }

            //刷新价格
            db("personday")->where(['id'=>$value['id']])->update(['hotel_json'=>json_encode($hotel_json)]);
        }
    }

    //通过利率和价格刷新总价
    public function refreshGoodsTotalPrice($goods_id)
    {
        //获取商品信息
        $goods = db("goods")->find($goods_id);
        if(empty($goods)) return false;

        //获取产品编码
        $product_code = $goods['goods_tcode']??"";
        if(empty($product_code)) return false;
        //获取产品信息
        $product = db("product")->where(['item_num'=>$product_code])->find();
        if(empty($product)) return false;
        //获取门票报价
        $scheduleData = (new SDModel())->getProductScheduleData($product['id']);
        $hasTicketPoiId = [];
        foreach ($scheduleData as $key=>$value){
            foreach ($value['children'] as $k=>$v){
                if($v['ticket_status']==1){
                    $hasTicketPoiId[] = $v['poiid'];
                }
            }
        }
        $ticketTotalCost = 0;
        //判断是否开启门票
        $specs = db('specs')->where('goods_id',$goods_id)->find();
        if(!empty($hasTicketPoiId) && !empty($specs) && $specs['vehicle_type']==2){
            $ticketData = (new SDModel())->getSectionTicketData($hasTicketPoiId);
            foreach ($ticketData as $ticket_k=>$ticket_v){
                $ticketTotalCost += $ticket_v['unitPrice'];
            }
        }
        $vehicle_rate = $goods['vehicle_rate'] ?? 1.25;
        $hotel_rate = $goods['hotel_rate'] ?? 1.1;
        $ticket_rate = $goods['ticket_rate'] ?? 1;
        $extra_rate = $goods['extra_rate'] ?? 1;
        $extra_fee = $goods['extra_fee'] ?? "";
        $extraCost = 0;
        if(!empty($extra_fee)){
            $extra_fee = explode(',',$extra_fee);
            foreach ($extra_fee as $ex_v){
                $extraCost += $ex_v;
            }
            $exchange_rate = $this->getExchangerateByCityId($goods['city_id']);
            $extraCost = ceil($extraCost*$exchange_rate*100)/100;
        }
        $personday = db("personday pd")
            ->join('person p','pd.person_id=p.person_id','left')
            ->field('pd.id,pd.vehicle_cost,pd.hotel_cost,pd.ticket_cost,extra_cost,p.people_num')
            ->where(['goods_id'=>$goods_id])->select();
        //开启事务
        db::startTrans();
        try{
            foreach ($personday as $day_key=>$day_value){
                //总售价
                $unitPrice = $this->calculateTotalPrice($day_value['vehicle_cost'],$vehicle_rate,$day_value['hotel_cost'],$hotel_rate,$ticketTotalCost,$ticket_rate,$extraCost,$extra_rate,$day_value['people_num']);
                //更新总价
                db("personday")->where(['id'=>$day_value['id']])->update([
                    "ticket_cost"=>$ticketTotalCost,
                    "extra_cost"=>$extraCost,
                    "person_price"=>$unitPrice
                ]);
            }
            //提交事务
            db::commit();
            return true;
        }catch (Exception $e){
            //回滚事务
            db::rollback();
            return false;
        }
    }

    //依据所属城市获取税率
    public function getExchangerateByCityId($cityid)
    {
        //获取税率
        $exchangelist = db('exchange')->select();
        $exchangeRate = [];
        $exCode = ["USD","CAD","NZD","JPY"];
        $countryName = ["美国","加拿大","新西兰","日本"];
        foreach ($exchangelist as $value){
            $index = array_search($value['currency_code'],$exCode);
            if($index >= 0) $exchangeRate[$countryName[$index]] = $value['exchange_rate'];
        }
        //根据城市获取父级城市
        $city = db('city')->find($cityid);
        while(!empty($city['groupid'])){
            $city = db('city')->find($city['groupid']);
        }
        if(empty($city['name'])) return 1;
        //目前税率包含美国 加拿大 日本 新西兰
        if(in_array($city['name'],$countryName)){
            return $exchangeRate[$city['name']]??1;
        }else{
            return 1;
        }
    }

    //依据所属城市获取币种
    public function getCurrencyByCityId($cityid)
    {
        //获取税率
        $countryName = [
            "美国"=>"USD",
            "加拿大"=>"CAD",
            "新西兰"=>"NZD",
            "日本"=>"JPY"
        ];
        //根据城市获取父级城市
        $city = db('city')->find($cityid);
        while(!empty($city['groupid'])){
            $city = db('city')->find($city['groupid']);
        }
        if(empty($city['name'])) return "CNY";
        //目前税率包含美国 加拿大 日本 新西兰
        if(key_exists($city['name'],$countryName)){
            return $countryName[$city['name']]??"CNY";
        }else{
            return "CNY";
        }
    }
}
